package com.zf.study.handler;

import com.zf.study.entity.ClientInfo;
import com.zf.study.message.HeartBeatMessage;

import java.util.concurrent.CopyOnWriteArrayList;

public class HeartBeatHandler implements Runnable {

    public static final CopyOnWriteArrayList<ClientInfo> clientList = new CopyOnWriteArrayList<ClientInfo>();

    @Override
    public void run() {
        //如果当前线程没有被打断，就循环发送心跳
        while (!Thread.currentThread().isInterrupted()) {
            long currentTime = System.currentTimeMillis();
            for (ClientInfo client : clientList) {
                try {
                    // 发送心跳请求
                    client.getWriter().println(HeartBeatMessage.HEARTBEAT_REQUEST);

                    // 检查是否超时
                    if (currentTime - client.getLastResponseTime() >
                            HeartBeatMessage.HEARTBEAT_INTERVAL * HeartBeatMessage.MAX_MISSED_HEARTBEATS) {
                        System.out.println("客户端 " + client.getTag() + " 心跳超时，将断开连接");
                        client.close();
                        clientList.remove(client);
                    }
                } catch (Exception e) {
                    System.out.println("发送心跳到客户端 " + client.getTag() + " 失败: " + e.getMessage());
                    clientList.remove(client);
                }
            }

            try {
                Thread.sleep(HeartBeatMessage.HEARTBEAT_INTERVAL);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }


    public static void addClient(ClientInfo client) {
        clientList.add(client);
    }

    public static void removeClient(ClientInfo client) {
        clientList.remove(client);
    }

    public static void updateLastResponseTime(String tag) {
        for (ClientInfo c : clientList) {
            if (c.getTag().equals(tag)) {
                c.setLastResponseTime(System.currentTimeMillis());
                break;
            }
        }
    }
}